package com.bit.net.component.data.client;

import com.bit.net.Message;
import com.bit.net.component.data.server.module.time.TimeRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.ReadTimeoutException;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

/**
 * 控制中心服务处理.
 *
 * @since 2018/10/10
 */
@Slf4j
public class DataClientResponseChannelHandler extends SimpleChannelInboundHandler<Message> {

    @Override
    protected void channelRead0(final ChannelHandlerContext ctx, Message msg) throws Exception {
        log.info("客户端接收到消息【{}】", msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(new TimeRequest().setMsg(UUID.randomUUID().toString()));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        if (cause instanceof ReadTimeoutException) {
            log.info("[client] idle, client:{}", ctx);
            ctx.channel().close();
            return;
        }

        log.error("[Game request] handle error", cause);

    }
}
